<?php
class UserVipShopService {

    /**
     * @var UserVipShopService
     */
    private static $instance;

    /**
     * Get the instance of UserVipShopService
     * @return UserVipShopService
     */
    public static function get() {
        if (!self::$instance) {
            self::$instance = new UserVipShopService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    public function __construct() {

    }

    /**
     * 清理玩家昨日数据
     * @param $userId
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function clearVipShop($userId,$reqTime) {
        $is_clear = false;

        /**
         * @var UserVipShopVo $userVipShop
         */

        //获取玩家vip商店数据
        $userVipShopList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_VIP_SHOP);
        if ($userVipShopList->getListCount() != 0){
            $userVipShopItems = $userVipShopList->toArray();
            $itemConfInfos = SzConfig::get()->loadAppConfig(GameConst::CONFIG_ITEM_VIP_SHOP, null, true);
            $monthConf = array();
            foreach ($itemConfInfos as $key=>$data){
                if (($data['type'] == 2)){//确定本月新花配置
                    if ($reqTime > $data['startTime'] && $reqTime < $data['endTime']){
                        $monthConf = $data;
                    }
                }
                else{
                    continue;
                }
            }

            //修正数据每日特惠多个和每月新花多个问题
            $saleNum = 0;
            $newNum = 0;
            foreach ($userVipShopItems as $key1=>$msgData1){
                if ($key1 == 0){
                    $userVipShopList->deleteElement($key1);
                    SzPersister::get()->setVoList($userVipShopList);
                    unset($userVipShopItems[$key1]);
                }
                if ($msgData1['isSale'] == 1){//每日折扣
                    $saleNum += 1;
                }
                if ($msgData1['isNew'] == 1){//每月新花
                    $newNum += 1;
                }
            }
            if ($saleNum > 1){
                foreach ($userVipShopItems as $key2=>$msgData2){
                    if ($msgData2['isSale'] == 1){//每日折扣
                        $userVipShopList->deleteElement($key2);
                        SzPersister::get()->setVoList($userVipShopList);
                        unset($userVipShopItems[$key2]);
                    }
                }
            }
            if ($newNum > 1){
                foreach ($userVipShopItems as $key3=>$msgData3){
                    if ($msgData3['isNew'] == 1 && $key3 != 65){//每月新花
                        $userVipShopList->deleteElement($key3);
                        SzPersister::get()->setVoList($userVipShopList);
                        unset($userVipShopItems[$key3]);
                    }
                }
            }
            //修正数据每日特惠多个和每月新花多个问题

            //进行删除数据
            foreach ($userVipShopItems as $itemId=>$data){
                $itemConfInfo = $itemConfInfos[$itemId];
                List($startToDay,$monthFirstTime,$monthLastTime) = $this->getTimePoint($reqTime);
                if ($itemConfInfo['type'] == 1 && $data['time'] < $startToDay){//每日折扣
                    $userVipShopList->deleteElement($itemId);
                    SzPersister::get()->setVoList($userVipShopList);
                    continue;
                }

                if (empty($monthConf)){
                    $monthConf = $itemConfInfo;
                }

                //特殊处理0529//修正数据已购买本月新花再次购买问题
                $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
                foreach ($itemList->toArray() as $hasId=>$item) {
                    if ($hasId != 41012177){
                        continue;
                    }
                    foreach ($item as $key=>$data1){
                        if ($data1['itemDefId'] == 41012177 && $data1['freeCount'] == 1){
                            $userVipShop = $userVipShopList->getElement(65,false);
                            if (!$userVipShop){
                                continue;
                            }
                            else{
                                $num = $userVipShop->getNum();
                                if ($num){
                                    continue;
                                }
                                else{
                                    $userVipShop->setNum(1);
                                    $userVipShopList->updateElement(65,$userVipShop);
                                    SzPersister::get()->setVoList($userVipShopList);
                                    continue;
                                }
                            }
                        }
                    }
                }
                //特殊处理0529//修正数据已购买本月新花再次购买问题

                if (($itemConfInfo['type'] == 2) && ($data['time'] < $monthConf['startTime'] || $data['time'] > $monthConf['endTime'])){//本月新花
                    $userVipShopList->deleteElement($itemId);
                    SzPersister::get()->setVoList($userVipShopList);
                    continue;
                }
            }
            $is_clear = true;
        }

        //整合返回数据
        return $is_clear;
    }

    /**
     * 获取vip商店购买数据
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function vipShopInfo($userId,$reqTime) {
        /**
         * @var ModuleProfileVo $profile
         * @var ModuleProfileInfoVo $refreshTimeInfo
         * @var UserVipShopVo $userVipShop
         */
        //获取玩家vip商店数据
        $userVipShopList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_VIP_SHOP);
        $has_sale = false;
        $has_new = false;

        $userVipShopItems = $userVipShopList->toArray();
        //获取今日，当月节点时间戳
        List($startToDay,$monthFirstTime,$monthLastTime) = $this->getTimePoint($reqTime);

        foreach ($userVipShopItems as $itemId=>$data){
            //获取配置
            $itemConfInfo = SzConfig::get()->loadAppConfig(GameConst::CONFIG_ITEM_VIP_SHOP, $itemId, true);
            if (empty($itemConfInfo)){
                continue;
            }

            if ($itemConfInfo['type'] == 1){//每日折扣
                $has_sale = true;
                if ($data['time'] < $startToDay){
                    $this->updateVipItem($userId,$userVipShopList,$data['itemId'],$itemConfInfo['type'],$reqTime);
                }
            }

            if ($itemConfInfo['type'] == 2){//每月新花
                $has_new = true;
                if ($data['time'] < $itemConfInfo['startTime'] || $data['time'] > $itemConfInfo['endTime']){
                    $this->updateVipItem($userId,$userVipShopList,$data['itemId'],$itemConfInfo['type'],$reqTime);
                }
            }

            if ($itemConfInfo['type'] == 0 && $data['time'] < $startToDay){//普通物品
                $this->updateVipItem($userId,$userVipShopList,$data['itemId'],$itemConfInfo['type'],$reqTime);
            }
        }

        if (!$has_new || !$has_sale){
            $confSet = array();
            $item = array();
            //生成每日特价和每月新花
            if (!$has_sale){
                $dayItemId = $this->getNewItemId(0,1,$reqTime);//今日特价
                $confSet[$dayItemId] = array('day'=>1,'month'=>0);
                $item[] = $dayItemId;
            }

            if (!$has_new){
                $monthItemId = $this->getNewItemId(0,2,$reqTime);
                $confSet[$monthItemId] = array('day'=>0,'month'=>1);
                $item[] = $monthItemId;
            }

            foreach ($item as $key){
                $userVipShop = $userVipShopList->getElement($key,false);
                if (!$userVipShop) {
                    $userVipShop = new UserVipShopVo(
                        $userId, // userId
                        $key, //itemId
                        $confSet[$key]['day'], // isSale
                        $confSet[$key]['month'], // isNew
                        0,//num
                        $reqTime,
                        true
                    );
                }

                if ($userVipShop->isInsert() && !SzUtility::checkArrayKey($key, $userVipShopList->getList())) {
                    $userVipShopList->addElement($userVipShop);
                    $userVipShopList->setElement($key,$userVipShop);
                }
            }
        }

        SzPersister::get()->setVoList($userVipShopList);

        //整合返回数据
        return array(
            'shopList'=>$userVipShopList->toArray()
        );
    }

    /**
     * 购买vip商店商品
     *
     * @param $userId 用户ID
     * @param $itemId 商品ID
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function buyVipShop($userId,$itemId,$reqTime)
    {
        /**
         * @var ModuleProfileVo $profile
         * @var UserVipShopVo $userVipShop
         */
        //获取商品配置
        $itemConfInfo = SzConfig::get()->loadAppConfig(GameConst::CONFIG_ITEM_VIP_SHOP, $itemId, true);
        if (empty($itemConfInfo)){
            throw new SzException(29030,$itemConfInfo['itemId']);//配置不存在
        }

        //玩家vip数据获取
        $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
        $profileInfo = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_MONTH_CARD, false);
        if ($profileInfo && ($reqTime >= (int)$profileInfo->getRawInfo())) {
            throw new SzException(29028);//月卡到期
        }

        $userVipShopList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_VIP_SHOP);
        $userVipShop = $userVipShopList->getElement($itemId,false);

        if (!$userVipShop) {
            $userVipShop = new UserVipShopVo(
                $userId, // userId
                $itemId, //itemId
                0, // isSale
                0, // isNew
                0,//num
                $reqTime,
                true
            );
        }
        $hasBuy = $userVipShop->getNum();
        //每日购买超过上限
        if (!is_null($userVipShop)){
            if ($hasBuy >= $itemConfInfo['times']){
                throw new SzException(29031);//没有库存
            }
        }

        $useGold = 0;//消耗钻石数量
        $outputTid = '';//获得tid
        $inputTid = '';//消耗tid

        //消耗资源
        if ($itemConfInfo['priceType'] == 1){
            GameService::get()->handleEntity($userId,GameConst::ENTITY_ACTION_CONSUME_MONEY, $itemConfInfo['price'], true);
            CommonFunctionService::get()->reportResourceUseDetails(17000072,$userId,0,GameConst::ENTITY_ACTION_CONSUME_MONEY.':'.$itemConfInfo['price'].'|','buyVipShop');//消耗资源上报

        }
        if ($itemConfInfo['priceType'] == 2){
            GameService::get()->handleEntity($userId,GameConst::ENTITY_ACTION_CONSUME_TICKET, $itemConfInfo['price'], true);
            CommonFunctionService::get()->reportResourceUseDetails(17000072,$userId,0,GameConst::ENTITY_ACTION_CONSUME_TICKET.':'.$itemConfInfo['price'].'|','buyVipShop');//消耗资源上报

        }


        //增加物品
        GameService::get()->handleEntity($userId,  $itemConfInfo['itemId'], $itemConfInfo['itemNum'],  true);
        CommonFunctionService::get()->reportResourceUseDetails(17000072,$userId,1,$itemConfInfo['itemId'].':'.$itemConfInfo['itemNum'].'|','buyVipShop');//消耗资源上报


        //数据入库
        $isNew = 0;
        $isSale = 0;
        if($itemConfInfo['type'] == 1){//每日打折
            $isNew = 0;
            $isSale = 1;
        }
        elseif ($itemConfInfo['type'] == 2){
            $isNew = 1;
            $isSale = 0;
        }

        $userVipShop->setIsNew($isNew);
        $userVipShop->setIsSale($isSale);
        $userVipShop->setNum($hasBuy + 1);
        $userVipShop->setTime($reqTime);
        if ($userVipShop->isInsert() && !SzUtility::checkArrayKey($itemId, $userVipShopList->getList())) {
            $userVipShopList->addElement($userVipShop);
            $userVipShopList->setElement($itemId,$userVipShop);
        } else {
            $userVipShopList->updateElement($itemId,$userVipShop);
        }

        SzPersister::get()->setVoList($userVipShopList);

        //社团竞赛任务进度添加
        UnionCompetitionService::get()->addCompetitionTaskProcess($userId,GameConst::UNION_COMPETITION_TASK_7, $reqTime,1);

        return true;
    }

    //获取时间节点
    public function getTimePoint($time){
        //今日开始时间&本月开始时间&结束时间
        $year = date("Y", $time);
        $month = date("m", $time);
        $day = date("d",$time);
        $num = date('t');// 本月一共有几天
        $startToDay = mktime(0,0,0,$month,$day,$year);
        $monthFirstTime = mktime(0, 0, 0, $month, 1, $year);     // 创建本月开始时间
        $monthLastTime = mktime(23, 59, 59, $month, $num, $year);  // 创建本月结束时间

        return array($startToDay,$monthFirstTime,$monthLastTime);
    }

    //更新玩家物品数据
    public function updateVipItem($userId,$userVipShopList,$oldItemId,$type,$reqTime){
        $itemId = $oldItemId;
//        $is_create = false;
//        $isNew = 0;
//        $isSale = 0;
//
//        if ($type == 1){
//            $itemId = $this->getNewItemId($oldItemId,$type);
//        }
//
//        if($type == 1){//每日打折
//            $isNew = 0;
//            $isSale = 1;
//        }
//        elseif ($type == 2){//每月新花
//            $isNew = 1;
//            $isSale = 0;
//        }

        $userVipShop = $userVipShopList->getElement($itemId,false);
//        if (!$userVipShop) {
////            $is_create = true;
//            $userVipShop = new UserVipShopVo(
//                $userId, // userId
//                $itemId, //itemId
//                0, // isSale
//                0, // isNew
//                0,//num
//                $reqTime,
//                true
//            );
//        }

        if ($type == 0){
            $userVipShop->setIsNew(0);
            $userVipShop->setIsSale(0);
        }
        if ($type == 1){
            $userVipShop->setIsNew(0);
            $userVipShop->setIsSale(1);
        }
        if ($type == 2){
            $userVipShop->setIsNew(1);
            $userVipShop->setIsSale(0);
        }
        $userVipShop->setNum(0);
        $userVipShop->setTime($reqTime);

//        if ($is_create){
//            $userVipShop->setIsNew($isNew);
//            $userVipShop->setIsSale($isSale);
//            //创建新数据
//            if ($userVipShop->isInsert() && !SzUtility::checkArrayKey($itemId, $userVipShopList->getList())) {
//                $userVipShopList->addElement($userVipShop);
//                $userVipShopList->setElement($itemId,$userVipShop);
//            }
//        }
//        else{
            $userVipShopList->updateElement($itemId,$userVipShop);
//        }
//        if($type == 1 || $type == 2){
//            $userVipShopList->deleteElement($oldItemId,false);
//            SzPersister::get()->setVoList($userVipShopList);
//            //获取新的商品数据
//            $itemId = $this->getNewItemId($oldItemId,$type);
//        }
//        $userVipShop = $userVipShopList->getElement($itemId,false);
//
//        $isNew = 0;
//        $isSale = 0;
//        if($type == 1){//每日打折
//            $isNew = 0;
//            $isSale = 1;
//        }
//        elseif ($type == 2){//每月新花
//            $isNew = 1;
//            $isSale = 0;
//        }
//
//        if (!$userVipShop) {
//            $userVipShop = new UserVipShopVo(
//                $userId, // userId
//                $itemId, //itemId
//                $isSale, // isSale
//                $isNew, // isNew
//                0,//num
//                $reqTime,
//                true
//            );
//        }
//
//        $userVipShop->setIsNew($isNew);
//        $userVipShop->setIsSale($isSale);
//        $userVipShop->setNum(0);
//        $userVipShop->setTime($reqTime);
//        //删除旧数据
//        if($type == 1 || $type == 2){
//            //创建新数据
//            if ($userVipShop->isInsert() && !SzUtility::checkArrayKey($itemId, $userVipShopList->getList())) {
//                $userVipShopList->addElement($userVipShop);
//                $userVipShopList->setElement($itemId,$userVipShop);
//            }
//        }
//        else{
//            //更新数据
//            $userVipShopList->updateElement($itemId,$userVipShop);
//        }
        SzPersister::get()->setVoList($userVipShopList);
    }

    //获取新的物品
    public function getNewItemId($oldItemId,$type,$reqTime){
        $itemId = 0;
        $vipShopConfigs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_ITEM_VIP_SHOP, null, true);

        $itemIdArr = array();
        foreach ($vipShopConfigs as $ormName => $itemConfig) {
            if ($type == 1){
                if ($itemConfig['type'] != 1){
                    continue;
                }

                if ($oldItemId != $ormName){
                    $itemIdArr[] = $ormName;
                }
            }
            if ($type == 2){
                //获取每月新花itemId
                if ($itemConfig['type'] != 2){
                    continue;
                }
                if ($reqTime <= $itemConfig['endTime'] && $reqTime >= $itemConfig['startTime']){
                    $itemId = $ormName;
                }
            }
        }

        if ($type == 1){
            $itemId = $itemIdArr[array_rand($itemIdArr)];
        }

        return $itemId;
    }
}